package  
{
	import flare.basic.*;
	import flare.collisions.*;
	import flare.core.*;
	import flare.primitives.*;
	import flare.system.*;
	import flash.display.*;
	import flash.events.*;
	import flash.geom.*;
	
	[SWF(frameRate = 120, backgroundColor = 0x808080, width = 800, height = 600 )]
	
	/**
	 * ...
	 * @author Ariel Nehmad
	 */
	public class Test11_MousePaint extends Sprite 
	{
		private var scene:Scene3D;
		private var mouse:MouseCollision;
		private var vector:Pivot3D;
		private var model:Pivot3D;
		
		public function Test11_MousePaint() 
		{
			scene = new Viewer3D( this );			
			model = scene.addChildFromFile( "mouse.f3d" );
			vector = scene.addChildFromFile( "vector.f3d" );
			scene.addEventListener( Scene3D.COMPLETE_EVENT, completeEvent );
		}
		
		private function completeEvent(e:Event):void 
		{
			mouse = new MouseCollision();
			mouse.addCollisionWith( model );
			
			scene.ambientColor = new Vector3D( 0.3, 0.3, 0.3 );
			scene.camera.setPosition( 50, 140, -150 );
			scene.camera.lookAt( 0, 0, 0 );				
			scene.addEventListener( Scene3D.UPDATE_EVENT, updateEvent );
		}
		
		private function updateEvent(e:Event):void 
		{
			if ( mouse.test( Input3D.mouseX, Input3D.mouseY ) )
			{
				// gets the first mouse collision info.
				var info:CollisionInfo = mouse.data[0];
				
				// access to the fisrt texture of the firts material.
				var texture:Texture3D = info.mesh.materials[0].textures[0];
				
				// the uv coords, are mapped from 0 to 1, so we need to multiply by the size of the texture.
				var u:Number = info.u * texture.bmp.width;
				var v:Number = info.v * texture.bmp.height;
				
				// draw some square over the texture at UV point.
				texture.bmp.fillRect( new Rectangle( u - 5, v - 5, 10, 10 ), Math.random() * 0xffffff );
				
				// because we did some changes on the texture, we need to
				// reupload again to the graphics card.
				texture.upload();
				
				/// additionaly, we align a 3d object to the point and normal of collision.
				vector.setPosition( info.point.x, info.point.y, info.point.z );
				vector.setNormalOrientation( info.normal );
			}
		}		
	}
}